<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Utils
 *
 * @author Antônio Braga
 */
class Fencer_Utils {

    public static function dataToDb($data){
         return self::dateFormat($data, 'Y-m-d');;
    }

    public static function moneyToDouble($money){
        $money = str_replace(array('R$', '.'), '', $money);
        $money = str_replace(',', '.', $money);
        return $money;
    }
    
    public static function dateFormat($data = null, $formato = 'd/m/Y', $soma = null)
    {
        if( strstr($data, '/') != '' ){
            $data = explode('/', $data);
            $data = "{$data[2]}-{$data[1]}-{$data[0]}";
        }

        $data = is_null($data) ? strtotime(date('Y-m-d')) : strtotime($data);

        if(!is_null($soma)){
            $data = $data+3600*24*$soma;
        }

        if('ext' == $formato){
            $oldlocale = setlocale(LC_ALL, NULL);

            setlocale(LC_ALL, 'pt_BR');
            $sem = ucwords(gmstrftime("%A",  $data));
            $mes = ucwords(gmstrftime("%B",  $data));
            $dia = ucwords(gmstrftime("%d",  $data));
            $ano = ucwords(gmstrftime("%Y",  $data));

            setlocale(LC_ALL, $oldlocale);
            return "{$sem}, {$dia} de {$mes} de {$ano}";
        }

        return date($formato, $data);
    }
    
    public static function removeCaracteres ($string){
    	
    	$string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
    	
    	return $string;
    }
    
    public static function getHoraAtual(){
    	ini_set('date.timezone','America/SAO_PAULO');
    	return date("H");
    }
    
    
    /**
     * Inverte a data de um formulário dd mm yyyy para yyyy mm dd. Além disso,
     * substitui o hífen '/' pela barra invertida '-'.
     * @param $date
     * @return string
     */
    
    public static function dateToDb($date) {
    
    	if ($date != '') {
    		if (strstr ( $date, '/' )) {
    			$date = explode ( '/', $date );
    			$invDate = "$date[2]-$date[1]-$date[0]";
    			return $invDate;
    		}
    	}
    	return $date;
    }

    /**
     * Retorna a URL base do sistema, ou seja, o caminho virtual.
     * Ex.:https://sistemas.cbm.df.gov.br/
     * @return String
     */
    public static function getBaseURL ()
    {
    	$front = Zend_Controller_Front::getInstance();
    	return self::getLink() . $front->getBaseUrl();
    }
    
    /**
     * Retorna o protocolo + servidor
     * Ex: https://thor
     * @return String
     */
    public static function getLink ()
    {
    	//Detecta o protocolo HTTP ou HTTPS.
    	$_SERVER['SERVER_PORT'] == '443' ? $protocolo = 'https://' : $protocolo = 'http://';
    	//Nome do servidor web.
    	$server = $_SERVER['SERVER_NAME'];
    	//Realiza as concatenacoes e monta a url.
    	$link = $protocolo . $server;
    	return $link;
    }
    
    public static function getPathSistema () {
    	return "C:/xampp/htdocs/siscave/";
    }
    
	/**
	 * Retorna todos os parametros do Request e aplica o filtro default
	 * @param String nome do parametro desejado
	 * @return mixed
	 */
	public static function getParams($arraynewFilters = null, Zend_Controller_Request_Abstract $request=null) {
		$arrayValue = $request ? $request->getParams() : Zend_Controller_Front::getInstance()->getRequest()->getParams();

		foreach ($arrayValue as $key => $value){
			$arrayValue[$key] = self::filtra($value, $arraynewFilters);
		}

		return $arrayValue;
	} 
	
	/**
	 * Retorna um parametro do Request e aplica o filtro default
	 * @param String nome do parametro desejado
	 * @return mixed
	 */
	public static function getParam($value, $arraynewFilters = null, Zend_Controller_Request_Abstract $request=null) {
		$value = $request ? $request->getParam($value) : Zend_Controller_Front::getInstance()->getRequest()->getParam($value);

		return self::filtra($value, $arraynewFilters);
	}	

	/**
	 * Filtro default para atributos GET do OpenID
	 * @param String valor a ser filtrado
	 * @return mixed
	 */
	public static function filtra($value, $arraynewFilters = null) {
		$filterChain = new Zend_Filter ( );
		$filterChain->addFilter ( new Zend_Filter_StringTrim ( ) )->addFilter ( new Zend_Filter_StripTags ( ) );

		if (isset ( $arraynewFilters )) {
			foreach ( $arraynewFilters as $filter ) {
				$filterChain->addFilter ( new $filter ( ) );
			}
		}

		if (is_array($value)){
			foreach ($value as $k => $v){
				$value[$k] = $filterChain->filter ( $v );
			}
		}else{
			return $filterChain->filter ( $value );
		}
		return $value;
	}

	/**
	 * 
	 * Cria uma estância do zend session.
	 * @return Object Zend_Session
	 */
	public static function getZendSession(){
		$session = new Zend_Session_Namespace();
		
		return $session;
	}
	
	/**
	 * 
	 * Retorna o cod_usuario logado no sistema
	 * @return String cod_usuario
	 */
	public static function getUsuarioId(){
		$session = self::getZendSession();

		return $session->dadosLogin["cod_usuario"];
	}
	
	/**
	 * 
	 * Retorna o nome do usuario logado
	 * @return String nome
	 */
	public static function getUsuarioNome(){
		$session = self::getZendSession();

		return $session->dadosLogin["nom_completo_pessoa"];
	}
}
